<!-- 数据引用拖拉拽页面 -->
<template>
    <div class="paper">
        <div class="graph-operate">
            <el-button :disabled="!curSelectNodeId" class="jtyj-btn-cancel" size="mini"
                @click="removeNode">删除</el-button>
        </div>
        <div ref="container" class="container" id="container"></div>
    </div>
</template>

<script>
var graph = null
import { v4 as uuidv4 } from "uuid";
export default {
    name: 'G6Graph',
    data() {
        return {
            curSelectNodeId: null,
            resizeObserver: null,
            nodes: [],
            edges: []
        };
    },
    props: {
        referenceList: {
            type: Array,
            default: () => []
        }
    },
    watch: {
        referenceList: {
            handler(newVal, oldVal) {
                this.initNodesAndEdges();
                this.initGraph();
            },
            deep: true,
            immediate: true
        }
    },
    created() {
    },
    mounted() {
        this.setupResizeObserver();
    },
    methods: {
        initNodesAndEdges() {
            this.nodes = [];
            this.edges = [];
            if (this.referenceList.length == 0) return;
            // 初始化主节点
            let temp = this.referenceList[0];
            this.nodes.push({
                id: 'node-' + temp.quoteModelId,
                data: {
                    category: "当前模型",
                    name: temp.quoteModelName,
                    version: temp.quoteMainVersionName,
                    active: false
                }
            })
            this.referenceList.forEach(item => {
                let uuid = uuidv4();
                this.nodes.push({
                    id: 'node-' + uuid,
                    data: {
                        dataQuoteId: item.dataQuoteId,
                        category: "被引用数据模型",
                        name: item.beQuoteModelName,
                        version: item.beQuoteMainVersionName,
                        modelData: item.beQuoteModelDataName,
                        active: false
                    }
                });
                this.edges.push({
                    id: 'edge-' + uuid,
                    labelText: item.beQuoteModelDataName,
                    source: 'node-' + uuid,
                    target: 'node-' + item.quoteModelId,
                })
            });
        },
        initGraph() {
            const { Graph, NodeEvent } = G6;
            if (graph) {
                graph.destroy();
            }
            graph = new Graph({
                autoFit: 'view',
                container: 'container',
                data: {
                    // nodes: [
                    //     { id: 'node-1', data: { category: '当前模型', name: '俺的森空军基地', version: '开发中', modelData: '', active: false } },
                    //     { id: 'node-2', data: { category: '被引用数据模型', name: '灰机', version: '开发中', modelData: '嗯呐？', active: false } },
                    //     { id: 'node-3', data: { category: '被引用数据模型', name: '跑道', version: '开发中', modelData: '哦哦？', active: false } },
                    // ],
                    // edges: [
                    //     { source: 'node-1', target: 'node-2' },
                    //     { source: 'node-1', target: 'node-3' },
                    //     { source: 'node-2', target: 'node-3' },
                    //     { source: 'node-3', target: 'node-2' },
                    // ],
                    nodes: this.nodes,
                    edges: this.edges
                },

                node: {
                    type: 'html',
                    style: {
                        size: [240, 100],
                        dx: 0,
                        dy: 0,
                        innerHTML: (d) => {
                            const {
                                data: { category, name, version, modelData, active },
                            } = d;

                            return `
                                <div 
                                style="
                                    width:100%; 
                                    height: 100%; 
                                    background: var(--ui-component-background-alt); 
                                    border: ${active ? '2px solid var(--app-primary-base)' : '1px solid var(--ui-border-color-base)'};
                                    color: var(--app-primary-base);
                                    user-select: none;
                                    display: flex; 
                                    flex-direction: column;
                                    padding: 10px;
                                    border-radius: 8px;
                                    "
                                >
                                    <div style="font-weight: bold; font-size: 14px;">
                                        ${category}
                                    </div>
                                    <div style="font-size: 12px; margin-top: 4px;">
                                        模型名称: ${name}
                                    </div>
                                    <div style="font-size: 12px; margin-top: 4px; margin-right: 8px;">
                                            模型版本: ${version}
                                    </div>
                            </div>`;
                        },
                    },
                },
                edge: {
                    type: 'quadratic',
                    style: {
                        labelText: (d) => d.labelText,
                        labelBackground: true,
                        labelBackgroundFill: 'rgba(250, 140, 22, 0.1)',
                        labelBackgroundRadius: 6,
                        labelPadding: [4, 8],
                        labelFill: '#D4380D',
                        labelPlacement: 'center',
                        endArrow: true,
                    },
                },
                layout: {
                    type: 'circular',
                },
                behaviors: [
                    'drag-element',
                    'zoom-canvas',
                    'drag-canvas'
                ],

            });
            graph.on(NodeEvent.CLICK, this.handleNodeClick);
            graph.render();
        },
        handleNodeClick(event) {
            const { target } = event;
            const nodes = graph.getNodeData();

            // 遍历并更新每个节点的数据
            nodes.forEach(node => {
                const active = node.id == target.id;
                graph.updateNodeData([{ id: node.id, data: { active } }]);
            });
            let curSelectNode = graph.getNodeData(target.id);
            if (curSelectNode.data.category != "当前模型") {
                this.curSelectNodeId = target.id;
            } else {
                this.curSelectNodeId = null;
            }
            graph.render();

        },
        async addNode() {
            graph.addNodeData([{ id: 'node' + Math.floor(Math.random() * 9999) + 1, data: { category: '从节点', name: '', status: '开发中', active: false } }]);
            await graph.render();

        },
        removeNode() {
            let curSelectNode = graph.getNodeData(this.curSelectNodeId);
            this.$emit('nodeRemove', curSelectNode.data.dataQuoteId);

        },
        setupResizeObserver() {
            const container = this.$refs.container;
            let resizeTimer = null;
            this.resizeObserver = new ResizeObserver(entries => {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(() => {
                    for (let entry of entries) {
                        const { width, height } = entry.contentRect;
                        if (graph) {
                            graph.setSize(width, height);
                            graph.render();
                        }
                    }
                }, 200);
            });
            this.resizeObserver.observe(container);
        }
    },

    beforeDestroy() {
        if (this.resizeObserver) {
            this.resizeObserver.disconnect();
        }
    }
};
</script>
<style lang="scss" scoped>
.paper {
    position: relative;
    width: 100%;
    height: 100%;

    .graph-operate {
        position: absolute;
        z-index: 999;
        top: 10px;
        right: 10px;
    }

    .container {
        width: 100%;
        height: 100%;
    }
}
</style>